class Deque {
  constructor() {
    this.count = 0;
    this.lowestCount = 0;
    this.items = {};
  }

  /*
   * front --> lowestCount 队首
   * back --> count 队尾
   */
  addFront(element) {
    if (this.isEmpty()) {
      // 当对象为空时，直接调用addBack，少写一些代码
      this.addBack(element);
    } else if (this.lowestCount > 0) {
      // 当 lowestCount 大于0时，说明指针到右侧，这个时候可以直接往左移
      this.lowestCount--;
      this.items[this.lowestCount] = element;
    } else {
      // 将每一项都向右移
      for (let i = this.count; i > 0; i--) {
        this.items[i] = this.items[i - 1];
      }
      // 一直将0项赋值为lowestCount
      this.lowestCount = 0;
      this.count++;
      this.items[0] = element;
    }
  }

  addBack(element) {
    this.items[this.count] = element;
    this.count++;
  }

  removeFront() {
    if (this.isEmpty()) {
      return undefined;
    }
    const result = this.items[this.lowestCount];
    delete this.items[this.lowestCount];
    this.lowestCount++;
    return result;
  }

  removeBack() {
    if (this.isEmpty()) {
      return undefined;
    }
    this.count--;
    const result = this.items[this.count];
    delete this.items[this.count];
    return result;
  }

  peekFront() {
    if (this.isEmpty()) {
      return undefined;
    }
    return this.items[this.lowestCount];
  }

  peekBack() {
    if (this.isEmpty()) {
      return undefined;
    }
    return this.items[this.count - 1];
  }

  isEmpty() {
    return this.size() === 0;
  }

  clear() {
    this.count = 0;
    this.lowestCount = 0;
    this.items = {};
  }

  size() {
    return this.count - this.lowestCount;
  }

  toString() {
    if (this.isEmpty()) {
      return '';
    }
    let objString = '';
    for (let i = this.lowestCount; i < this.count; i++) {
      objString += `${i} : ${this.items[i]} , `;
    }
    return objString;
  }
}

// const deque = new Deque();
// console.log(deque.isEmpty());
// deque.addBack('John');
// deque.addBack('Jack');
// console.log(deque.toString());
// deque.addBack('Camila');
// console.log(deque.toString());
// console.log(deque.size());
// console.log(deque.isEmpty());
// deque.removeFront();
// console.log(deque.toString());
// deque.removeBack();
// console.log(deque.toString());
// deque.addFront('John');
// console.log(deque.toString());

module.exports = Deque;
